call(), apply(), bind() 的用法

[转载] javascript中call()、apply()、bind()的用法终于理解(自我觉得整理后比原作者更好,当然原作者也是很厉害的,简单粗暴的讲清楚了~)

call()、apply()、bind()是三种重新定义this指针指向的方法。

先捋一波this指针的指向:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var name = "小王", age = 17
var obj = {
name: "小张",
objAge: this.age, // 此处的this指针指向window
myFun: function(){
console.log(this.name + "年龄" + this.age) // 此处的this指针指向object
}
}
console.log(obj.objAge) // 输出 17
obj.myFun() // 输出 小张年龄undefined

var str = "Hello"
function greet(){
console.log(this.str) // 此处的this指针指向window
}
greet() // 输出 Hello

可见,this指针默认指向使用者所挂载的对象

然后就是call()、apply()、bind()三个方法的使用对比:

1
2
3
4
5
6
7
8
9
10
11
12
13
var obj = {
name: "小张",
myFun: function(address, phone){
console.log(this.name + "年龄" + this.age + ",住在" + address + ",电话" + phone)
}
}
var newObj = {
name: "小李",
age: 20
}
obj.myFun.call(newObj, "上海", "110") // 输出 小李年龄20,住在上海,电话110
obj.myFun.apply(newObj, ["上海", "110"]) // 输出 小李年龄20,住在上海,电话110
obj.myFun.bind(newObj, "上海", "110")() // 输出 小李年龄20,住在上海,电话110

总结:
1) call、bind、apply三个函数的第一个参数定义了this指针的指向对象;
2) 从第二个参数起都是函数传参(允许各种类型,函数、对象都可),call和bind用逗号分隔传入,apply用数组传入;
3) call和apply直接执行函数,返回执行结果;bind返回的是新的函数,需要调用才执行。